/**
 * 离线操作
 * Created by WMM on 2018/06/18.
 */
import { Component, ElementRef } from '@angular/core';
import { IonicPage, NavController, ToastController, NavParams, AlertController, LoadingController, App } from 'ionic-angular';
import { OfflineDataApi } from '../../api/offline-data/OfflineDataApi';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite'
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
import { LoginApi } from '../../api/login/LoginApi';
import { AddressApi } from "../../api/login/AddressApi";

@IonicPage()
@Component({
  selector: 'page-offline-cache',
  templateUrl: 'offline-cache.html'
})
export class OfflineCache {
  myAppDatabase: SQLiteObject;

  private user: object;
  private userName: string;
  private pwd: string;
  private logininfo: string[];
  private LeaveTag: boolean = true;
  private userInfoTag: boolean = false;
  private cacheBtnTag: boolean = true;
  private onlineBtnTag: boolean = false;
  //  页面即将进入时调用
  ionViewWillEnter() {
    this.getData();
  }

  //  页面离开时调用
  ionViewWillUnload() {
    if (this.onlineBtnTag) {
      const http$ = this.loginApi.out(this.userName);
      http$.subscribe((val: any) => {
        let res = JSON.parse(val);
        if (res.state) {
          localStorage.removeItem("token");
          localStorage.removeItem("userInfo");
        }
      });
    }
  }

  //  离开页面守卫
  ionViewCanLeave(): boolean {
    return this.LeaveTag;
  }

  constructor(public addressApi: AddressApi, private barcodeScanner: BarcodeScanner, public loginApi: LoginApi, private sqlite: SQLite, public offlineDataApi: OfflineDataApi, private app: App, private ele: ElementRef, public navCtrl: NavController, private loadingCtrl: LoadingController, private alertCtrl: AlertController, public params: NavParams, private toastCtrl: ToastController) {
    this.user = {
      name: "",
      company: ""
    }
  }

  getData() {
    this.sqlite.create({
      name: 'ionicdb.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      db.executeSql('CREATE TABLE IF NOT EXISTS materiel(rowid INTEGER PRIMARY KEY ,date TEXT,companyId VARCHAR,name TEXT,code TEXT,qrcode TEXT,length decimal(50,2), width decimal(50,2), height decimal(50,2),emptyWeight decimal(50,3),volume decimal(50,3),takePhoto INT,materielId VARCHAR,pklmaterielId VARCHAR)', [])
        .then(res => console.log('初始化表 materiel'))
        .catch(e => console.log(e.message));
      db.executeSql('CREATE TABLE IF NOT EXISTS container(rowid INTEGER PRIMARY KEY ,date TEXT,companyId ,id VARCHAR,name TEXT,code TEXT, qrcode TEXT,length decimal(50,3), width decimal(50,2), height decimal(50,2),deadWeight decimal(50,3),bearWeight decimal(50,3),containerType INT)', [])
        .then(res => console.log('初始化表 container'))
        .catch(e => console.log(e.message));
      this.myAppDatabase = db;
    }).catch(e =>
      this.showMsg("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message)
    );
  }


  refreshCache() {
    let now = new Date();
    let loading = this.loadingCtrl.create({
      content: '下载中,请耐心等待...'
    });
    loading.present();
    this.offlineDataApi.refreshCache().subscribe(res => {
      if (res.state) {
        let success = true;
        this.myAppDatabase.transaction(tx => {
          tx.executeSql('DELETE FROM materiel WHERE companyId=?',
            [res.companyId]
            , () => {
              //  console.log('删除materiel ');
            }
            , e => {
              //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
              success = false;
            }
          );
          tx.executeSql('DELETE FROM container WHERE companyId=?',
            [res.companyId]
            , () => {
              //  console.log('container ');
            }
            , e => {
              //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
              success = false;
            }
          );
          let materiels: [any] = res.materiels;
          if (materiels != null || materiels.length > 0) {
            for (var materiel of materiels) {
              tx.executeSql('INSERT INTO materiel VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                [this.myFormat('yyyy-MM-dd hh:mm:ss', now), materiel.companyId, materiel.materielName, materiel.materielCode, materiel.materielQrcode, materiel.length, materiel.width, materiel.height, materiel.emptyWeight, materiel.volume, materiel.takePhoto, materiel.materielId, materiel.id]
                , () => {
                  //  console.log('insert into materiel table successfully');
                }
                , e => {
                  //  console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
                  success = false;
                }
              );
            }
          }
          let containers: [any] = res.containers;
          if (containers != null || containers.length > 0) {
            for (var container of containers) {
              tx.executeSql('INSERT INTO container VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?)',
                [this.myFormat('yyyy-MM-dd hh:mm:ss', now), container.companyId, container.id, container.containerName, container.containerCode, container.qrcode, container.longs, container.wide, container.high, container.deadWeight, container.bearWeight, container.containerType]
                , () => {
                  // console.log('insert into container table successfully');
                }
                , e => {
                  // console.log("系统Sql组件错误,请联系管理员!,错误信息为: " + e.message);
                  success = false;
                }
              );
            }
          }
        })
          .then(res => console.log('更新缓存结束'))
          .catch(e => console.log(e));
        loading.dismiss();
        if (success) {
          this.showMsg("更新成功!");
        } else {
          this.showMsg("更新失败!请保证网络通畅后再试！");
        }
      } else {
        loading.dismiss();
        this.showMsg(res.msg);
      }
    });
  }


  doLogin() {
    const http$ = this.loginApi.auth(this.userName, this.pwd);
    http$.subscribe((val: any) => {
      let loginResult = JSON.parse(val);
      if (loginResult.state) {
        this.showMsg("登陆成功,正在缓存...");
        localStorage.setItem("token", loginResult.token);
        localStorage.setItem("userInfo", loginResult.userInfo);
        this.offlineDataApi.getAppUserInfo().subscribe(res => {
          this.user = res;
          this.userInfoTag = true;
          this.cacheBtnTag = false;
        });
        this.onlineBtnTag = true;
        this.refreshCache();
      } else {
        this.showMsg(loginResult.msg);
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
      }
    });
  }


  scanLogin() {
    this.barcodeScanner.scan({ showTorchButton: true, resultDisplayDuration: 0 }).then((data) => {
      if (data.text.length != 0) {
        this.logininfo = data.text.split("丨");
        if (this.logininfo.length == 2) {
          this.userName = this.logininfo[0];
          this.pwd = this.logininfo[1];
          this.ele.nativeElement.querySelector("#dologin").click();
        } else {
          this.showMsg("请扫描正确的二维码!");
        }
      } else {
        this.fixshowMsg("请扫描正确的二维码!");
      }
    }, (err) => {
      this.showMsg("扫描出现异常" + err);
    });
  }

  fixshowMsg(msg: string) {
    this.LeaveTag = false;
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
    setTimeout(() => this.LeaveTag = true, 1000);
  }

  switchUser() {
    const http$ = this.loginApi.out(this.userName);
    http$.subscribe((val: any) => {
      let res = JSON.parse(val);
      if (res.state) {
        this.cacheBtnTag = true;
        this.userInfoTag = false;
        this.onlineBtnTag = false;
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        this.userName = "";
        this.pwd = "";
      } else {
        this.showMsg("系统出错,请重试!");
      }
    });
  }


  goOnline() {
    if (!this.onlineBtnTag) {
      this.showMsg("请先登录！");
    } else {
      let alert = this.alertCtrl.create({
        title: '使用在线功能请确保网络通畅!',
        message: "点击确定进行GPS选择位置!",
        buttons: ['取消',
          {
            text: '确定',
            handler: data => {
              this.gpsAddress();
            }
          }]
      });
      alert.present();
    }

  }

  /**
   * 进行gps定位，去服务器获取最近的位置列表供用户选择
   */
  gpsAddress() {
    var options = {
      enableHighAccuracy: true,  // 是否使用 GPS
      maximumAge: 60000,         // 缓存时间
      timeout: 27000,            // 超时时间
      coorType: 'bd09ll'         // 默认是 gcj02，可填 bd09ll 以获取百度经纬度用于访问百度 API
    }
    navigator.geolocation.getCurrentPosition((position: any) => {
      if (<string>position.coords.latitude == "5e-324" || <string>position.coords.longitude == "5e-324" || <string>position.coords.latitude == "4.9E-324" || <string>position.coords.longitude == "4.9E-324") {
        const alert = this.alertCtrl.create({
          title: '定位失败!，请检查位置功能与权限是否打开！',
          subTitle: '位置功能》》设置-位置-开启  位置权限》》设置-权限-应用-定位—开启',
          buttons: ['确定']
        });
        alert.present();
        return;
      }
      this.addressApi.getAddress(<string>position.coords.latitude, <string>position.coords.longitude).subscribe(res => {
        let result = JSON.parse(res);
        if (result.state) {
          this.showMsg("定位成功,正在链接服务器获取最近位置信息...");
          let addresses = result.data;
          this.doSelectAddress(addresses);
        } else {
          this.showMsg("10公里内无项目地点!");
        }
      });
    }, (error: any) => {
      this.showMsg(error);
    }, options);
  }

  /**
   * 用户进行位置选择，选择完毕后进入下一个页面：项目计划列表页。
   * @param {object[]} addresses
   */
  doSelectAddress(addresses: object[]) {
    let alert = this.alertCtrl.create();

    alert.setTitle('请选择您所在的位置');
    for (var index in addresses) {
      let item: any = addresses[index];
      alert.addInput({
        type: 'radio',
        label: item.positionName,
        value: item.id,
        checked: parseInt(index) == 0 ? true : false
      });
    }

    alert.addButton({
      text: '确定',
      handler: (data: any) => {
        this.navCtrl.setRoot('ProjectPlan', { "position": data, "userName": this.userName }, {
          animate: true,
          direction: 'forward'
        });
      }
    });
    alert.present();
  }

  //点击取消返回
  goBack() {
    // this.ele.nativeElement.querySelector("[ng-reflect-klass='back-button']").click();
    this.navCtrl.pop();
  }

  showMsg(msg: string) {
    var toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom'
    });
    toast.present();
  }

  myFormat(fmt: string, data: Date) {
    var o = {
      "M+": data.getMonth() + 1,                 //月份
      "d+": data.getDate(),                    //日
      "h+": data.getHours(),                   //小时
      "m+": data.getMinutes(),                 //分
      "s+": data.getSeconds(),                 //秒
      "q+": Math.floor((data.getMonth() + 3) / 3), //季度
      "S": data.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (data.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }


}
